<?php
namespace app\channel\controller;
use think\Db;

class Index extends Base
{
    public function index(){
        $whereMenu = 'status=1';

        //不是一级渠道
        if(session('admin.cps_pid')!=0){
            $whereMenu .= " && title<>'游戏礼包' && title<>'对账管理' && title<>'二级渠道管理'";
        }

        //是联运渠道
        if(session('admin.sdk_id') && !session('admin.cps_id')){
            $whereMenu .= " && title<>'渠道管理' && title<>'对账管理' && title<>'游戏列表'";
        }

        //特殊渠道开通更新神兽功能
        /*
        $arr = [
            1000
            ,5070
            ,5118
            ,5027
            ,1082
            ,5005
            ,5112
            ,1085
            ,5203
            ,5102
            ,1085
            ,5119
            ,5072
            ,5120
            ,5087
            ,5107
            ,5013
            ,1164
            ,5007
            ,5063
            ,5078
            ,1769
            ,5024
            ,5064
            ,2128
            ,1271
            ,1451
            ,5052
            ,1950
            ,5073
            ,5040
            ,2182
            ,5016
            ,5081
            ,5068
        ];
        if(session('admin.cps_id')){
            if(!in_array(session('admin.cps_id'), $arr)){
                $whereMenu .= " && title<>'更新神兽'";
            }
        }else if(session('admin.sdk_id')){
            if(!in_array(session('admin.sdk_id'), $arr)){
                $whereMenu .= " && title<>'更新神兽'";
            }
        }*/

        $menuList = Db::name('ChannelMenu')->where($whereMenu)->order('sort desc')->select();
        import('cate.Category');
        $leftMenu = \Category::unlimitedForLayer($menuList, $name='list', 1);

        $isLockScreen = cookie('is_lock_screen') ? true : false;
        $vipUrl = Db::name('GameMaterial')->where('type', 2)->value('url');

        //今日数据
        if(session('admin.cps_id') && session('admin.sdk_id')){
            $cpsData = $this->selectCps();
            $sdkData = $this->selectSdk();

            $data = [
                'game_add' => $cpsData['game_add']+$sdkData['game_add'],
                'game_active' => $cpsData['game_active']+$sdkData['game_active'],
                'pay_number' => $cpsData['pay_number']+$sdkData['pay_number'],
                'pay_money' => $cpsData['pay_money']+$sdkData['pay_money'],
            ];
        }else if(session('admin.cps_id')){
            $data = $this->selectCps();
        }else if(session('admin.sdk_id')){
            $data = $this->selectSdk();
        }

        $today = ['game_add'=>$data['game_add'], 'game_active'=>$data['game_active'], 'pay_number'=>$data['pay_number'], 'pay_money'=>$data['pay_money']/100];

        $skinName = cookie('skin_name') ? cookie('skin_name') : '';
        return view('', ['today'=>$today, 'vip_url'=>$vipUrl, 'login'=>session('admin'), 'skin_name'=>$skinName, 'is_lock_screen'=>$isLockScreen, 'leftMenu'=>$leftMenu]);
    }

    private function selectCps(){
        $startTime = strtotime(date('Y-m-d', time()));
        $endTime = time();
        $year = date('Y', $startTime);
        $month = date('Ym', $startTime);

        $allChannelId = model('manage/Channel')->allChannelId( session('admin.cps_id') );
        $whereAdd = "bond_time between {$startTime} AND {$endTime} && channel_id=1000 && cps_id in ({$allChannelId})";
        $whereActive = "in_time between {$startTime} AND {$endTime} && channel_id=1000 && cps_id in ({$allChannelId})";
        $whereOrder = "pay_time between {$startTime} AND {$endTime} AND debug=0 AND pay_result=1 && channel_id=1000 && reg_cps_id in ({$allChannelId})";

        $add = Db::name('GameUserY_'.$year)
            ->field("count(*) AS game_add")
            ->where($whereAdd)
            ->find();


        $active = Db::name('GameUserLogM_'.$month)
            ->field("count(DISTINCT(my_user_id)) AS game_active")
            ->where($whereActive)
            ->find();

        $order = Db::name('PayOrderY_'.$year)
            ->field("count(DISTINCT(my_user_id)) AS pay_number,sum(total_price) AS pay_money")
            ->where($whereOrder)
            ->find();

        return ['game_add'=>$add['game_add'], 'game_active'=>$active['game_active'], 'pay_number'=>$order['pay_number'], 'pay_money'=>$order['pay_money'] ? $order['pay_money'] : 0];
    }

    private function selectSdk(){
        $startTime = strtotime(date('Y-m-d', time()));
        $endTime = time();
        $year = date('Y', $startTime);
        $month = date('Ym', $startTime);

        $sdkId = session('admin.sdk_id');
        $whereAdd = "bond_time between {$startTime} AND {$endTime} && channel_id={$sdkId}";
        $whereActive = "in_time between {$startTime} AND {$endTime} && channel_id={$sdkId}";
        $whereOrder = "pay_time between {$startTime} AND {$endTime} AND debug=0 AND pay_result=1 && channel_id={$sdkId}";

        $add = Db::name('GameUserY_'.$year)
            ->field("count(*) AS game_add")
            ->where($whereAdd)
            ->find();

        $active = Db::name('GameUserLogM_'.$month)
            ->field("count(DISTINCT(my_user_id)) AS game_active")
            ->where($whereActive)
            ->find();

        $order = Db::name('PayOrderY_'.$year)
            ->field("count(DISTINCT(my_user_id)) AS pay_number,sum(total_price) AS pay_money")
            ->where($whereOrder)
            ->find();

        return ['game_add'=>$add['game_add'], 'game_active'=>$active['game_active'], 'pay_number'=>$order['pay_number'], 'pay_money'=>$order['pay_money'] ? $order['pay_money'] : 0];
    }

    public function quit(){
        session('admin', null);
        $this->redirect('Show/login');
    }

    public function notice(){
        $page = input('page');
        $limit = input('limit');
        $noticeType = input('notice_type');

        $where['status'] = 1;
//        $where['id'] = ['<>', 384];
        !empty($noticeType) && $where['notice_type'] = $noticeType;

        if( ! $count=Db::name('ChannelNotice')->where($where)->count() ){
            $this->layTable();
        }

        $select = Db::name('ChannelNotice')
            ->where($where)
            ->order('release_time desc')
            ->limit(($page-1)*$limit, $limit-1)
            ->select();

//        $select2 = Db::name('ChannelNotice')->where('id', 384)->select();
//        $select = array_merge($select2, $select1);

        $data = [];
        $noticeType = config('notice_type');
        $noticeGrade = config('notice_grade');
        foreach ($select as $k=>$v){
            //如果发布时间大于一周前的时间，显示小红点
            $point = $v['release_time']>strtotime('-7 days') ? 1 : 0;

            $data[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'content' => $v['content'],
                'release_time' => date('Y-m-d H', $v['release_time']) . ':00',
                'author' => $v['author'],
                'notice_type' => $noticeType[ $v['notice_type'] ],
                'notice_grade' => $noticeGrade[ $v['notice_grade'] ],
                'status' => $v['status'],
                'point' => $point,
            ];
        }

        $this->layTable(0, '公告列表', $data, $count+1);
    }

    public function server(){
        $page = input('page');
        $limit = input('limit');
        $weekType = input('week_type');

        if(cache('data')){
            $json = cache('data');
        }else{
            $params = array('sign' => md5('c0ac1f407ebb3ef98f7cc7f01f3195d5'));
            $httpArr = http('http://www.miyuhaiwai.com/api/open-servers', $params, 'post', array(), true);
            $json = json_decode($httpArr, true);
            cache('data', $json, 60); //缓存时间为60秒
        }
        if(input('?export')){
            foreach ($json['data'][$weekType] as $k => $v) {
                if( $v['expect'] == 3 ) continue;

                $excelData[] = array(
                    'open_time' => $v['open_time'],
                    'game_name' => $v['game_name'],
                    'platform_id' => $v['platform_id'],
                    'area' => $v['area'],
                );
            }
            array_unshift($excelData,['开服时间', '游戏名称', '区服编号', '区服名称']);

            //获取当周星期一到星期天的时间
            $week = date('w')==0 ? 'last week' : 'this week';
            $monday = date('Y-m-d', strtotime($week));
            $sunday = date('Y-m-d', strtotime($week . '+7 days'));
            $monday = str_replace('-', '', $monday);
            $sunday = str_replace('-', '', $sunday);
            exportExcel($excelData,"{$monday}-{$sunday}开服表","{$monday}-{$sunday}开服表");
            exit;
        }
        $data = array_slice($json['data'][$weekType], ($page-1)*$limit, $limit);
        $count = count($json['data'][$weekType]);

        $this->layTable(0, '开服列表', $data, $count);
    }

    public function pwd() {
        if( request()->isAjax() ){
            $pwd = input('password');
            $pwdConfirm = input('password_confirm');
            if($pwd !== $pwdConfirm){
                $this->layJson(1, '两次密码不一致');
            }else if( !preg_match('/^[a-zA-Z0-9_-]{4,20}$/', $pwd) ){
                $this->layJson(1, '由4-20位（字母，数字，下划线，减号）组成');
            }

            $pwd = md5($pwd);

            if(session('admin.cps_id') && session('admin.sdk_id')){
                Db::name('Channel')->where(['channel_id'=>1000, 'cps_id'=>session('admin.cps_id')])->update(['password'=>$pwd]);
                Db::name('Channel')->where(['channel_id'=>session('admin.sdk_id')])->update(['password'=>$pwd]);
            }else if(session('admin.cps_id')){
                Db::name('Channel')->where(['channel_id'=>1000, 'cps_id'=>session('admin.cps_id')])->update(['password'=>$pwd]);
            }else if(session('admin.sdk_id')){
                Db::name('Channel')->where(['channel_id'=>session('admin.sdk_id')])->update(['password'=>$pwd]);
            }

            $this->layJson(0, '修改成功，请重新登录');
        }else{
            return view();
        }
    }
}
